package xcmg.device.service.userinfo;

import com.github.pagehelper.PageInfo;
import yb.ecp.fast.infra.util.PageHelperPlus;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import xcmg.device.dao.mapper.userinfo.LoginInfoMapper;
import xcmg.device.infra.ExportUtil;
import xcmg.device.service.vo.userinfo.AbnormalLoginVO;
import xcmg.device.service.vo.userinfo.AgentLoginLogsQueryVO;
import xcmg.device.service.vo.userinfo.LoginLogQeuryParamVO;
import xcmg.device.service.vo.userinfo.LoginLogQueryResultVO;
import xcmg.device.service.vo.userinfo.LoginLogStatisticVO;
import xcmg.device.service.vo.userinfo.UserLoginLogDetailsQueryParamVO;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class LoginInfoService {

    @Autowired
    private LoginInfoMapper loginInfoMapper;

    public PageCommonVO<LoginLogQueryResultVO> getUserLoginLogs(SearchCommonVO<LoginLogQeuryParamVO> condition){
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        LoginLogQeuryParamVO filters = condition.getFilters();
        List<LoginLogQueryResultVO> loginLogQueryResults = loginInfoMapper.selectLogList(filters);
        PageCommonVO<LoginLogQueryResultVO> result = new PageCommonVO();
        result.setPageInfo(new PageInfo(loginLogQueryResults));
        result.setPageInfoList(loginLogQueryResults);
        return result;
    }

    /**
     * @Des 经销商登录信息统计
     * @Date 2021/4/7 15:12
     * @Author wangzhaoyu
     * @Param []
     * @Return yb.ecp.fast.infra.infra.PageCommonVO<xcmg.device.service.vo.userinfo.LoginLogStatisticVO>
     */
    public PageCommonVO<LoginLogStatisticVO> getAgentLoginStatics(SearchCommonVO<AgentLoginLogsQueryVO> condition){
        Integer pageNum = condition.getPageNum();
        Integer pageSize = condition.getPageSize();
        PageHelperPlus.startPage(pageNum, pageSize);
        List<LoginLogStatisticVO> loginLogStatistics = loginInfoMapper.selectAgentLoginStatics(condition.getFilters());
        PageCommonVO result = new PageCommonVO();
        result.setPageInfo(new PageInfo(loginLogStatistics));
        result.setPageInfoList(loginLogStatistics);
        return result;
    }

    /**
     * @Des 经销商登录信息统计
     * @Date 2021/4/7 15:12
     * @Author wangzhaoyu
     * @Param []
     * @Return yb.ecp.fast.infra.infra.PageCommonVO<xcmg.device.service.vo.userinfo.LoginLogStatisticVO>
     */
    public void agentLoginStaticsExportAll(AgentLoginLogsQueryVO filter, HttpServletResponse response) throws Exception {
        List<LoginLogStatisticVO> loginLogStatistics = loginInfoMapper.selectAgentLoginStatics(filter);
        invokeStaticsExport(loginLogStatistics,response);
    }

    public void agentLoginDetailsExportAll(AgentLoginLogsQueryVO filter,HttpServletResponse response) throws Exception {
        List<LoginLogQueryResultVO> loginLogQueryResults = loginInfoMapper.selectAgentLoginDetail(filter);
        invokeDetailExport(loginLogQueryResults,response);
    }

    public PageCommonVO<LoginLogStatisticVO> getUserLoginStatics(SearchCommonVO<LoginLogQeuryParamVO> condition){
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        LoginLogQeuryParamVO filters = condition.getFilters();
        List<LoginLogStatisticVO> loginLogStatisticVOS = loginInfoMapper.selectLogStatics(filters);
        PageCommonVO<LoginLogStatisticVO> result = new PageCommonVO();
        result.setPageInfo(new PageInfo(loginLogStatisticVOS));
        result.setPageInfoList(loginLogStatisticVOS);
        return result;
    }

    public void userLoginStaticsExport(LoginLogQeuryParamVO filter, HttpServletResponse response) throws Exception {
        List<LoginLogStatisticVO> loginLogStatisticVOS = loginInfoMapper.selectLogStatics(filter);
        if(CollectionUtils.isEmpty(loginLogStatisticVOS)){
            return ;
        }
        invokeStaticsExport(loginLogStatisticVOS,response);

    }

    public void userLoginDetailExport(LoginLogQeuryParamVO filter, HttpServletResponse response) throws Exception {
        List<LoginLogQueryResultVO> loginLogQueryResults = loginInfoMapper.selectLogList(filter);
        invokeDetailExport(loginLogQueryResults,response);
    }

    private void invokeDetailExport(List<LoginLogQueryResultVO> loginLogQueryResults,HttpServletResponse response) throws Exception {
        String title = "登录记录详情信息导出";
        String[] rowsName = new String[] { "序号", "登录名称", "登录ip", "ip归属地", "登录时间", "真实姓名"};
        List<Object[]> dataList = new ArrayList<Object[]>();
        Object[] objs;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for ( int i = 0; i < loginLogQueryResults.size(); i++ ){
            LoginLogQueryResultVO detailInfo = loginLogQueryResults.get( i );
            objs = new Object[rowsName.length];
            objs[0] = i + 1;
            objs[1] = detailInfo.getLoginName();
            objs[2] = detailInfo.getLoginIp();
            objs[3] = detailInfo.getIpHome();
            Date loginDate = detailInfo.getLoginDate();
            String loginDateStr = loginDate == null ? null : sdf.format(loginDate);
            objs[4] = loginDateStr;
            objs[5] = detailInfo.getUserName();
            dataList.add( objs );
        }
        ExportUtil exportUtil = new ExportUtil( title, rowsName, dataList );
        exportUtil.export( response );
    }

    private void invokeStaticsExport(List<LoginLogStatisticVO> loginLogStatisticVOS, HttpServletResponse response) throws Exception {

        String title = "登录记录统计信息导出";
        String[] rowsName = new String[] { "序号", "登录名称", "真实姓名", "公司名称", "登录次数"};
        List<Object[]> dataList = new ArrayList<Object[]>();
        Object[] objs;
        for ( int i = 0; i < loginLogStatisticVOS.size(); i++ )
        {
            LoginLogStatisticVO statisticInfo = loginLogStatisticVOS.get( i );
            objs = new Object[rowsName.length];
            objs[0] = i + 1;
            objs[1] = statisticInfo.getLoginName();
            objs[2] = statisticInfo.getUserName();
            objs[3] = statisticInfo.getCompanyName();
            objs[4] = statisticInfo.getLoginCount();
            dataList.add( objs );
        }
        ExportUtil exportUtil = new ExportUtil( title, rowsName, dataList );
        exportUtil.export( response );
    }

    public PageCommonVO<LoginLogQueryResultVO> getloginDetails(SearchCommonVO<UserLoginLogDetailsQueryParamVO> condition) {
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        UserLoginLogDetailsQueryParamVO filters = condition.getFilters();
        List<LoginLogQueryResultVO> loginLogQueryResults = loginInfoMapper.selectByUserId(filters);
        PageCommonVO result = new PageCommonVO();
        result.setPageInfo(new PageInfo(loginLogQueryResults));
        result.setPageInfoList(loginLogQueryResults);
        return result;
    }

    /**
     * @Des 获取异常登录的信息：
     *  思路：使用最简单的逻辑，登录成功后调用接口，查询最后两条，粗略认为最新的一条为当前用户登录的ip,倒数第二条为当前用户前一次登录的记录，
     *  如果最后两条的ip不同，则认为倒数第二条为异常的登录记录
     * @Date 2021/4/7 14:30
     * @Author wangzhaoyu
     * @Param [userId]
     * @Return xcmg.device.service.vo.userinfo.AbnormalLoginVO
     */
    public AbnormalLoginVO getAbnormalLogin(String userId){
        try{
            if(StringUtils.isEmpty(userId)){
                return null;
            }
            List<LoginLogQueryResultVO> loginLogQueryResultVOS = loginInfoMapper.lastedTwoLoginRecord(userId);
            if(CollectionUtils.isEmpty(loginLogQueryResultVOS) || loginLogQueryResultVOS.size() < 2){
                return null;
            }
            String latestLoginIp = loginLogQueryResultVOS.get(0).getLoginIp();
            String beforeLoginIp = loginLogQueryResultVOS.get(1).getLoginIp();
            if(StringUtils.isEmpty(beforeLoginIp) || StringUtils.isEmpty(latestLoginIp) || latestLoginIp.equals(beforeLoginIp)){
                return null;
            }
            LoginLogQueryResultVO loginLogQueryResultVO = loginLogQueryResultVOS.get(1);
            AbnormalLoginVO result = new AbnormalLoginVO();
            result.setIpHome(loginLogQueryResultVO.getIpHome());
            result.setLoginDate(loginLogQueryResultVO.getLoginDate());
            result.setLoginIp(loginLogQueryResultVO.getLoginIp());
            return result;
        }catch (Exception e){
            return null;
        }
    }
}
